package cn.zy.gvs.v1.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.zy.gvs.v1.core.common.base.BaseController;
import cn.zy.gvs.v1.core.common.domain.AjaxResult;
import cn.zy.gvs.v1.core.utils.SaTokenUtil;
import cn.zy.gvs.v1.model.SysUser;
import cn.zy.gvs.v1.service.ISysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("${gvs.apiPrefix}/sys")
public class LoginController extends BaseController {

    @Autowired
    private ISysUserService iSysUserService;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody SysUser user) {
        // 判断是否登陆
        if (StpUtil.isLogin()) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userinfo", SaTokenUtil.getUser());
            map.put("token", StpUtil.getTokenInfo());
            return success().put("data", map);
        } else {
            if (StrUtil.isNotBlank(user.getUsername()) && StrUtil.isNotBlank(user.getPassword())) {
                SysUser sysUser = iSysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getUsername, user.getUsername())
                        .eq(SysUser::getPassword, SecureUtil.md5(user.getPassword()))
                        .last("LIMIT 1"));
                if (sysUser != null) {
                    // 用户登录
                    StpUtil.login(sysUser.getId());
                    // 设置session
                    SaTokenUtil.setUser(sysUser);
                    Map<String, Object> map = new HashMap<>();
                    map.put("userinfo", sysUser);
                    map.put("token", StpUtil.getTokenInfo());
                    return success().put("data", map);
                } else {
                    return error(301, "账户或者密码错误");
                }
            } else {
                return error(302, "账户密码不能为空");
            }
        }
    }


    @GetMapping("/logout")
    public AjaxResult logout() {
        // 判断是否登陆
        StpUtil.logout();
        return success();
    }


    @GetMapping("/getOssInfo")
    public AjaxResult getOssInfo() {

        return success();
    }
}
